//index.js
var app = getApp();
// var WxParse = require('../../utils/wxParse/wxParse.js');
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    modalName:'',
    painting: {},
    shareImage: '',
    detail: '',
    userInfo: '',
    id: '',
    imgUrl:''
  },
  onLoad(options) {
    var _this = this;
    var id = options.id;
    //  var userinfomation = wx.getStorageSync('user_info')
    console.log(id)
    _this.setData({
      id: id,
    })
    var openid = getApp().globalData.openid;
    if (!openid) {
      wx.showModal({
        title: '提示',
        content: '本功能需要授权后才可使用，点击确定跳转到登录界面',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            // setTimeout(function () {
            //   wx.switchTab({
            //     url: '/pages/member/index',
            //   });
            // }, 500)
            _this.showModal()
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.navigateBack()
          }
        }
      })
      return;
    } else {
      this.loadDetail()
    }
  },

  loadDetail() {
    const _this = this
    var id = this.data.id;
    var openid = getApp().globalData.openid
    app.core('get', 'xiaochengxu_article_detail/id/' + id + '/openid/' + openid + '', {}, (res) => {
      console.log(res)
      _this.setData({
        detail: res.data
      })
      var id = res.data.id;
      var url = res.data.album_txt[0];
      // console.log(url)
      if(url){
        _this.setData({
          imgUrl: url
        })
      }else{
        _this.setData({
          imgUrl: 'https://xkcloude.hfhouse.com/storage/advert/2019-09-26/cSOGFmhGXjoz56Y7HNZGia0oi701IXhDFx0uNizE.jpeg'
        })
      }

      setTimeout(() => {
        _this.eventDraw()
      },1000)
    })
  },
  eventDraw() {
    wx.showLoading({
      title: '绘制海报中...',
      mask: true
    })
    var that = this;
    var detail = this.data.detail;
    var ctime = detail.created_at;
    var content = detail.content.replace(/\s+/g,"");
    console.log(detail.visit)
    var timearr = ctime.split(' ');
    console.log(timearr[0])
    var userinfomation = wx.getStorageSync('userInfo');
    var imgUrl = this.data.imgUrl;
    var code = this.data.detail.code;
    // console.log(imgUrl)
    this.setData({
      painting: {
        width: 375,
        height: 633,
        clear: true,
        views: [
          {
            type: 'image',
            url:         'https://xkcloude.hfhouse.com/storage/advert/2019-09-17/6uxrKJhTGSG21neAzkqmHJ97VqQKgD3WXeMHKwi3.png',
            top: 0,
            left: 0,
            width: 375,
            height: 633
          },
          {
            type: 'image',
            url: userinfomation.avatarUrl,
            top: 493,
            left: 35,
            width: 58,
            height: 58,
          },
          {
            type: 'text',
            content: userinfomation.nickName,
            fontSize: 13,
            color: '#034AB5',
            textAlign: 'left',
            top: 503,
            left: 100,
          },
          {
            type: 'text',
            content: '正在分享这篇文章',
            fontSize: 13,
            color: '#034AB5',
            textAlign: 'left',
            top: 526,
            left: 100
          },
          {
            type: 'image',
            url: imgUrl,
            top: 126,
            left: 19,
            width: 335,
            height: 195,
          },
          {
            type: 'image',
            url: code,
            top: 493,
            left: 250,
            width: 100,
            height: 100
          },
          {
            type: 'text',
            content: detail.title,
            fontSize: 22,
            lineHeight: 25,
            color: '#034AB5',
            textAlign: 'left',
            top: 32,
            left: 30,
            width: 280,
            MaxLineNumber: 2,
            breakWord: true,
            bolder: true
          },
          {
            type: 'text',
            content: '发布者：' + detail.xiaochengxu_user.nickname + '  ' + timearr[0] ,
            fontSize: 16,
            color: '#2E2E2E',
            textAlign: 'left',
            top: 92,
            left: 30,
            width: 280,
            breakWord: true,
            bolder: true
          },
          // {
          //   type: 'text',
          //   content: detail.visit,
          //   fontSize: 16,
          //   color: '#2E2E2E',
          //   textAlign: 'left',
          //   top: 110,
          //   left: 130,
          // },
          {
            type: 'text',
            content: content,
            fontSize: 16,
            lineHeight: 24,
            color: '#383549',
            textAlign: 'left',
            top: 338,
            left: 38,
            width: 287,
            MaxLineNumber: 5,
            breakWord: true,
          },
          {
            type: 'text',
            content: '长按小程序码查看详情 分享自【星房惠】',
            fontSize: 13,
            color: '#2E65AC',
            textAlign: 'left',
            top: 580,
            left: 25,
            width: 125,
            bolder:true
          }
        ]
      }
    })
  },
  eventSave() {
    var id = this.data.id;
    console.log(id)
    // console.log(this.data.shareImage)
    // let _this = this;
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareImage,
      success(res) {
        wx.showToast({
          title: '保存图片成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.switchTab({
            url: '/pages/write/index',
          });
        }, 1000)
      },
      fail(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData", failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }
          })
        }
      },
    })
  },
  eventGetImage(event) {
    console.log(event)
    wx.hideLoading()
    const { tempFilePath, errMsg } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
  },
  previewImg(e) {
    var current = e.target.dataset.src;
    console.log(current)
    wx.previewImage({
      current: current,
      urls: [this.data.shareImage]
    })
  },
  // share() {
  //   wx.updateShareMenu({
  //     withShareTicket: true,
  //     success(res) {
  //       console.log(res)
  //     }
  //   })
  // }


  showModal(e) {
    this.setData({
      modalName: 'DialogModal1'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
    wx.navigateBack()
  },
  getUserInfo: function (e) {
    console.log(e)
    var vm = this;
    var UserInfo = e.detail.userInfo
    // wx.setStorageSync('userInfo', e.detail.userInfo)
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          var userCode = res.code;
          var referrer = wx.getStorageSync('referrer')
          app.core('post', 'create_xcx_user', {
                'nickname': UserInfo.nickName,
                'headpic': UserInfo.avatarUrl,
                'js_code': userCode,
                'referrer': referrer
              }, (res) => {
                console.log(res)
                // return false
                console.log("open_id" + res.data.open_id);
                wx.setStorageSync('userInfo', e.detail.userInfo);
                console.log(wx.getStorageSync('userInfo'));
                wx.setStorageSync('user_new', res.data.open_id);
                wx.setStorageSync('sessionKey', res.sessionKey);
                console.log(wx.getStorageSync('user_new'))

                getApp().globalData.openid = res.data.open_id

                vm.setData({
                  userInfo: e.detail.userInfo,
                  hasUserInfo: true,
                  isMain: true,
                  isPower: wx.getStorageSync('user_new')
                });
                wx.hideLoading()
                vm.setData({
                  modalName: null
                })

                vm.loadDetail()
              },
              (err) => {
                console.log(err)
              }
          )

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
})
